package com.example.zhinongbao.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;

import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;


import com.bumptech.glide.Glide;
import com.example.zhinongbao.Model.ShoppingCartImpl;
import com.example.zhinongbao.R;
import com.example.zhinongbao.database.DBHelper;
import com.example.zhinongbao.entity.Cart;
import com.example.zhinongbao.entity.Goods;
import com.example.zhinongbao.entity.Photo;
import com.example.zhinongbao.presenter.ShoppingCartPresenter;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ShoppingCartActivity extends AppCompatActivity {
    private ImageView backBtn ;
    private TextView managerBtn , payTotal ;
    private ListView listView ;
    private Button payBtn ;
    private LinearLayout cartBottom ;
    private ArrayAdapter<Cart> adapter ;
    private List<Cart> cartList ;
    private ShoppingCartPresenter presenter ;
    private final ArrayList<Integer> idList = new ArrayList<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shopping_cart);
        initView();
//点击数量弹窗输入数量
//        final EditText editText1 = new EditText(this);
//        editText1.setHint("输入在此处");
//        SharedPreferences sharedPreferences = getSharedPreferences("user", Context.MODE_PRIVATE);
//        String phone = sharedPreferences.getString("username" , "");

        ShoppingCartImpl shoppingCartImpl = new ShoppingCartImpl(this);
        presenter = new ShoppingCartPresenter(shoppingCartImpl);

        refreshData();

        managerBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String manText = managerBtn.getText().toString();
                if (manText.equals("编辑")){
                    managerBtn.setText("完成");
                    payBtn.setBackgroundColor(ContextCompat.getColor(ShoppingCartActivity.this,R.color.limegreen));
                    payBtn.setText("删除");
                    cartBottom.setVisibility(View.GONE);
                } else if (manText.equals("完成")) {
                    managerBtn.setText("编辑");
                    payBtn.setBackgroundColor(ContextCompat.getColor(ShoppingCartActivity.this,R.color.red));
                    payBtn.setText("结算");
                    cartBottom.setVisibility(View.VISIBLE);
                }
            }
        });


        payBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String action = managerBtn.getText().toString();
                if (action.equals("编辑")){
                  Toast.makeText(ShoppingCartActivity.this,"结算功能未开发",Toast.LENGTH_SHORT).show();
                } else if (action.equals("完成")) {
                    if (!idList.isEmpty()){
                        new android.app.AlertDialog.Builder(ShoppingCartActivity.this)
                                .setMessage("确定删除吗？")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        for (int id : idList){
                                            presenter.deleteCartById(id);
                                        }
                                        idList.clear();
                                        refreshData();
                                        Toast.makeText(ShoppingCartActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                                    }
                                })
                                .setNegativeButton("取消", null)
                                .create().show();
                    }else {
                        Toast.makeText(ShoppingCartActivity.this, "请选择删除对象", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });


        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idList.clear();
                onBackPressed();
            }
        });

    }

    private void refreshData(){

        cartList = presenter.getCartByPhone();
        cartAdapter(); // 确保适配器被初始化
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
    private void showTotal(){
        double needPayMoney = 0 ;
        if (!idList.isEmpty()){
            for (int id : idList){
                Cart cart  = presenter.getCartById(id);
                Goods goods = presenter.getGoodsById(cart.getGoodsId());
                needPayMoney = needPayMoney + (goods.getPrice() * cart.getNum());
                payTotal.setText(String.valueOf(needPayMoney));
            }
        }else {
            payTotal.setText("0");
        }
    }

    private void cartAdapter(){


        adapter = new ArrayAdapter<Cart>(this , R.layout.shopping_cart_item , R.id.cart_item_name , cartList){
            @SuppressLint("Range")
            public View getView(int position , View converView , ViewGroup parent){
                View view = super.getView(position, converView, parent);
                CheckBox addList = view.findViewById(R.id.cart_item_checkBox);
                ImageView goodsImg = view.findViewById(R.id.cart_item_img);
                TextView goodsName = view.findViewById(R.id.cart_item_name);
                TextView goodsId = view.findViewById(R.id.cart_item_id);
                ImageButton minus = view.findViewById(R.id.cart_item_minus);
                TextView goodsNum = view.findViewById(R.id.cart_item_num);
                ImageButton add = view.findViewById(R.id.cart_item_add);
                TextView money = view.findViewById(R.id.cart_item_money);
                goodsNum.setText("1");
                Cart cart = getItem(position);
                assert cart != null;
//                goodsNum.setText(String.valueOf(cart.getNum()));
                Goods goods = presenter.getGoodsById(cart.getGoodsId());

                if (goods != null){
                    money.setText(String.valueOf(goods.getPrice()));

                    goodsName.setText(goods.getName());
                    goodsId.setText(String.valueOf(goods.getId()));
                    goodsId.setText(String.valueOf(goods.getId()));

                    // 获取商品的第一张图片并设置到ImageView
                    List<Photo> photoList = goods.getPhotoList(); // 假设这是从Goods对象获取图片列表的方法
                    if (photoList != null && !photoList.isEmpty()) {
                        Photo firstPhoto = photoList.get(0);
                        if (firstPhoto != null) {
                            // 调用compressBitmap方法压缩图片，这里需要传递图片的字节数据
                            Bitmap compressedBitmap = compressBitmap(firstPhoto.getData(), 800, 800);
                            // 将压缩后的图片设置到ImageView
                            goodsImg.setImageBitmap(compressedBitmap);
                        }

                    }

                }

                addList.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (addList.isChecked()){
//                            if (managerBtn.getText().toString().trim().equals("编辑")){
//
//                            } else if (managerBtn.getText().toString().trim().equals("完成")) {
//                                idList.add(cart.getId());
//                            }
                            idList.add(cart.getId());
                            showTotal();

                        }else {
                            Iterator<Integer> iterator = idList.iterator();
                            while (iterator.hasNext()){
                                Integer id = iterator.next();
                                if (id.equals(cart.getId())){
                                    iterator.remove();
                                    showTotal();
                                }
                            }
                        }

                    }
                });

                goodsImg.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(ShoppingCartActivity.this, ProductDetailsActivity.class);
// 假设 Goods 对象有一个 getId() 方法来获取商品的 ID
                        intent.putExtra("goodsId", goods.getId());
                        startActivity(intent);


                    }
                });


                minus.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int num = Integer.parseInt(goodsNum.getText().toString());
                        if (num >1){
                            num = num - 1 ;
                            goodsNum.setText(String.valueOf(num));
                            money.setText(String.valueOf(goods.getPrice() * num ));
                            presenter.updateCartNumById(cart.getId() , num);
                            showTotal();
                        }else {
                            Toast.makeText(ShoppingCartActivity.this, "亲，不能再少了", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int num = Integer.parseInt(goodsNum.getText().toString());
                        num = num + 1 ;
                        goodsNum.setText(String.valueOf(num));
                        money.setText(String.valueOf(goods.getPrice() * num ));
                        presenter.updateCartNumById(cart.getId() , num);
                        showTotal();
                    }
                });
                goodsNum.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(ShoppingCartActivity.this);
                        builder.setMessage("输入商品数量");
                        final EditText editText = new EditText(ShoppingCartActivity.this);
                        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
                        builder.setView(editText);
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String getNum = editText.getText().toString().trim();
                                if (getNum.isEmpty()){
                                    Toast.makeText(ShoppingCartActivity.this, "请输入需求数量", Toast.LENGTH_SHORT).show();
                                }else {
                                    int num = Integer.parseInt(getNum);
                                    if (num >= 1){
                                        goodsNum.setText(getNum);
                                        money.setText(String.valueOf(goods.getPrice() * num));
                                        presenter.updateCartNumById(cart.getId() , num);
                                        Cart cart1 = presenter.getCartById(cart.getId());
                                        cartList.set(position , cart1);
                                        adapter.notifyDataSetChanged();
                                        showTotal();
                                    }else {
                                        Toast.makeText(ShoppingCartActivity.this, "商品数量输入不规范", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }
                        });
                        builder.create().show();
                    }
                });
                managerBtn.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {

                    }

                    @Override
                    public void afterTextChanged(Editable s) {
                        if(addList.isChecked()){
                            addList.setChecked(false);
                        }
                    }
                });
                return view ;
            }
        };
    }

    private Bitmap compressBitmap(byte[] photoData, int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(photoData, 0, photoData.length, options);

        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeByteArray(photoData, 0, photoData.length, options);
    }

    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // 计算inSampleSize值
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // 计算出实际的inSampleSize值
            while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }


    private void initView(){
        backBtn = findViewById(R.id.cart_back);
        managerBtn = findViewById(R.id.cart_manager);
        payBtn = findViewById(R.id.cart_pay) ;
        payTotal = findViewById(R.id.cart_total);
        listView = findViewById(R.id.cart_listView);
        cartBottom = findViewById(R.id.cart_bottom);
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshData();
    }


}